package com.yc.hwc.web;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.yc.hwc.bean.Comment;
import com.yc.hwc.bean.PageImpl;
import com.yc.hwc.bean.Result;
import com.yc.hwc.bean.Task;
import com.yc.hwc.bean.TaskLog;
import com.yc.hwc.bean.User;
import com.yc.hwc.web.remote.ITaskDo;
import com.yc.hwc.web.remote.IUserDo;
import com.yc.util.Utils;

@Controller
public class IndexDo {

	@Resource
	private IUserDo iud;

	@Resource
	private ITaskDo itld;

	@GetMapping
	String index() {
		return "index";
	}

	@GetMapping("/go_{page}")
	String topage(@PathVariable String page) {
		return "back/" + page;
	}

	@GetMapping("/to_{page}")
	String topage(@PathVariable String page, HttpServletRequest request) {
		if ("login".equals(page) && request.getSession().getAttribute("savedUri") == null) {
			String path = request.getHeader("Referer");
			if (!"login".equals(path)) {
				request.getSession().setAttribute("savedUri", request.getHeader("Referer"));
			}
		}
		/*
		 * URL url = getClass().getClassLoader().getResource("templates"); File root =
		 * new File(url.toString().replace(url.getProtocol() + ":/", "")); File file =
		 * findFile(root, page); String path = file.toString().replace(root.toString(),
		 * "").replace(".html", ""); return path.replaceAll("\\\\", "/");
		 */
		return page;
	}

	/*
	 * private File findFile(File dir, String page) { File[] fs = dir.listFiles(new
	 * FilenameFilter() {
	 * 
	 * @Override public boolean accept(File dir, String name) { return
	 * name.equalsIgnoreCase(page + ".html"); } }); if (fs.length > 0) { return
	 * fs[0]; } else { fs = dir.listFiles(new FileFilter() {
	 * 
	 * @Override public boolean accept(File pathname) { return
	 * pathname.isDirectory(); } }); for (File f : fs) { File ret = findFile(f,
	 * page); if (ret != null) { return ret; } } return null; } }
	 */

	@PostMapping("login")
	@ResponseBody
	Result<?> login(User user, HttpSession session) {
		Result<?> res = iud.login(user);
		if (res.getCode() == 1) {
			session.setAttribute("loginedUser", res.getData());
		}
		return res;
	}

	@PostMapping("setpwd")
	@ResponseBody
	Result<?> setpwd(User user, @SessionAttribute User loginedUser) {
		if (loginedUser.getPwd().equals(user.getPwd()) == false) {
			return Result.failure("原密码错误！");
		}
		if (user.getClsSn().matches(".{6,12}") == false) {
			return Result.failure("新密码长度必须是6~12位！");
		}
		if (user.getClsSn().equals(user.getHead()) == false) {
			return Result.failure("确认密码与新密码不一致！");
		}
		String oldpwd = loginedUser.getPwd();
		loginedUser.setPwd(user.getClsSn());
		Result<?> ret = iud.save(loginedUser);
		if (ret.getCode() == 1) {
			return Result.success("密码修改成功！");
		} else {
			loginedUser.setPwd(oldpwd);
			return ret;
		}
	}

	@GetMapping("myTask")
	@ResponseBody
	PageImpl<Task> myTask(@SessionAttribute User loginedUser, Task task, int page, int size) {
		Utils.setBean(task, "clsSn", loginedUser.getClsSn());
		return itld.myTaskList(task, page, size);
	}

	@GetMapping("myTaskLog")
	@ResponseBody
	List<TaskLog> myTaskLog(@SessionAttribute User loginedUser, TaskLog tasklog) {
		Utils.setBean(tasklog, "inUser.id", loginedUser.getId());
		return itld.findTaskLog(tasklog).getContent();
	}

	@Value("${upload-dir}")
	private String uploadDir;

	@PostMapping("upload")
	@ResponseBody
	Result<?> upload(@RequestParam("file") MultipartFile mf, @SessionAttribute(required = false) User loginedUser) {
		String path = uploadDir;
		String webpath = "";
		String name = mf.getOriginalFilename();
		if (loginedUser != null) {
			webpath = loginedUser.getClsSn() + "/" + loginedUser.getName() + "/";
			path += webpath;
		} else {
			int i = name.lastIndexOf(".");
			String suffix = null;
			if (i > 0) {
				suffix = name.substring(i);
			}
			name = UUID.randomUUID().toString().replaceFirst("-", "");
			name += suffix != null ? suffix : "";

		}
		File dir = new File(path);
		if (dir.exists() == false && dir.mkdirs() == false) {
			System.out.println("创建上传目录失败:" + dir);
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.success("创建上传目录失败！", null);
		}
		File file = new File(dir, name);
		try {
			mf.transferTo(file);
			Object ret = Utils.map(
					// Upload 对象字段
					"webPath", webpath + name, "oldName", name, "newName", name, "RelaTable", "task_log",
					// Layui 富文本编辑需要字段
					"src", webpath + name, "title", name);
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.failure("文件上传成功！", ret);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.success("文件上传失败！", null);
		}

	}

	@PostMapping("commit")
	@ResponseBody
	Result<?> commit(TaskLog tl, @SessionAttribute User loginedUser) {
		tl.setInUser(loginedUser);
		return itld.save(tl);
	}

	@PostMapping("reply")
	@ResponseBody
	Result<?> reply(Comment cmt, @SessionAttribute(required = false) User loginedUser) {
		cmt.setInUser(loginedUser);
		return itld.reply(cmt);
	}

	@RequestMapping("logout")
	String logout(HttpSession session) {
		session.invalidate();
		return "redirect:" + this.buildRedirectPath("/");
	}

	@RequestMapping("getLoginedUser")
	@ResponseBody
	User getLoginedUser(@SessionAttribute(required = false) User loginedUser) {
		return loginedUser;
	}

	@RequestMapping("task/save")
	@ResponseBody
	Result<?> saveTask(Task task, @SessionAttribute(required = false) User loginedUser) {
		if (loginedUser != null) {
			task.setInUser(loginedUser);
		}
		return itld.save(task);
	}

	@GetMapping("continue")
	String toContinue(HttpSession session) {
		String savedUri = (String) session.getAttribute("savedUri");
		if (savedUri == null) {
			savedUri = buildRedirectPath("/");
		} else {
			session.removeAttribute("savedUri");
			savedUri = buildRedirectPath(savedUri);
		}
		return "redirect:" + savedUri;
	}

	@RequestMapping("getTaskLog")
	@ResponseBody
	TaskLog getTaskLog(TaskLog taskLog, @SessionAttribute(required = false) User loginedUser) {
		if (loginedUser == null) {
			return new TaskLog();
		} else {
			taskLog.setInUser(loginedUser);
			PageImpl<TaskLog> page = itld.findTaskLog(taskLog);
			if (page.isEmpty()) {
				return new TaskLog();
			} else {
				return page.getContent().get(0);
			}
		}

	}

	@Value("${zuul.host}")
	private String host;
	@Value("${zuul.post}")
	private int post;

	public String buildRedirectPath(String path) {
		return path = path.startsWith("http") ? path : String.format("http://%s:%s" + path, host, post);
	}

}
